﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Three.BookStore.RBAC;
using System.Linq;
using System.Collections.Generic;
using Three.BookStore.RBAC.DTOs;

namespace Three.BookStore.Web.Control
{
    public class HomeController : Controller
    {
        private readonly IMenuServices _menuServices;
        private readonly ILogger<HomeController> _logger;

        public HomeController(IMenuServices menuServices, ILogger<HomeController> logger)
        {
            _menuServices = menuServices;
            _logger = logger;
        }

        public async Task<IActionResult> Index()
        {
            var allMenus = await _menuServices.ShowMenu();
            
            _logger.LogInformation($"Retrieved {allMenus.Count} menus from service");
            
            // 构建菜单树
            var rootMenus = allMenus.Where(m => m.ParentId == null).ToList();
            _logger.LogInformation($"Found {rootMenus.Count} root menus");
            
            foreach (var rootMenu in rootMenus)
            {
                rootMenu.Children = GetChildMenus(allMenus, rootMenu.Id);
                _logger.LogInformation($"Root menu {rootMenu.Name} has {rootMenu.Children.Count} children");
            }
            
            return View(rootMenus);
        }

        public IActionResult Login()
        {
            return View();
        }

        public IActionResult Welcome()
        {
            // 使用ViewResult代替Content，并确保显示r.jpg图片
            ViewBag.Title = "欢迎使用Three ERP系统";
            return View("Welcome");
        }

        private List<MenuDto> GetChildMenus(List<MenuDto> allMenus, int parentId)
        {
            var childMenus = allMenus.Where(m => m.ParentId == parentId).ToList();
            _logger.LogInformation($"Found {childMenus.Count} children for parent ID {parentId}");
            
            foreach (var childMenu in childMenus)
            {
                childMenu.Children = GetChildMenus(allMenus, childMenu.Id);
                _logger.LogInformation($"Child menu {childMenu.Name} has {childMenu.Children.Count} sub-children");
            }
            return childMenus;
        }
    }
}
